package global

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"path/filepath"
	"runtime"
)

type Config struct {
	Server     Server     `yaml:"server"`
	TLS        TLS        `yaml:"tls"`
	Mysql      Mysql      `yaml:"mysql"`
	HttpServer HttpServer `yaml:"http-server"`
	Redis      Redis      `yaml:"redis"`
	Point      Point      `yaml:"point"`
}

type Server struct {
	Host      string `yaml:"host"`
	Port      int    `yaml:"port"`
	LogStatus bool   `yaml:"log-status"`
	LogPath   string `yaml:"log-path"`
}

type TLS struct {
	Enabled  bool   `yaml:"enabled"`
	CertFile string `yaml:"cert-file"`
	KeyFile  string `yaml:"key-file"`
}

type Mysql struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	DbName   string `yaml:"dbname"`
}

type HttpServer struct {
	Host    string `yaml:"host"`
	Port    int    `yaml:"port"`
	HostUrl string `yaml:"host-url"`
}

type Redis struct {
	Host string `yaml:"host"`
	Port int    `yaml:"port"`
	DB   int    `yaml:"db"`
}

type Point struct {
	AdminUrl  string `yaml:"admin-url"`
	AppKey    string `yaml:"app-key"`
	AppSecret string `yaml:"app-secret"`
}

var basePath string

func init() {
	_, currentFile, _, _ := runtime.Caller(0)
	basePath = filepath.Dir(currentFile)
}

func ReadConfig() *Config {

	// 读取YAML文件
	yamlFile, err := ioutil.ReadFile("config/config.yaml")
	if err != nil {
		fmt.Println("Error reading YAML file:", err)
	}

	var config Config
	// 解析 YAML数据

	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		fmt.Println("Error parsing YAML:", err)
	}

	return &config
}

func Path(rel string) string {
	if filepath.IsAbs(rel) {
		return rel
	}

	return filepath.Join(basePath, rel)
}
